<template>
  <!--
  <sysDict  type="sex" value="1"/>

  -->

  <span>
    {{ dictNames.join(",") }}
  </span>
</template>
<script>
import { getDictName, putDict } from "@/utils/dict";
import { getByTypeValue } from '@/api/sys/dict'
export default {
  name: "sysDict",
  data() {
    return {
      name: "",
      dictNames: []
    };
  },
  watch: {
    value: {
      //深度监听，可监听到对象、数组的变化
      handler(val, oldVal) {
        if (
          val != null &&
          val != "" &&
          val != undefined &&
          val != "undefined"
        ) {
          this.init(val);
        } else {
          this.dictNames = [];
        }
      },
      deep: true
    }
  },
  props: ["type", "value"],
  created() {
    // 计算数据字典的名称
    this.init(this.value);
  },
  methods: {
    init(val) {
      if (val != null) {
        this.dictNames = [];
        var vals = (val + "").split(",");
        for (var i in vals) {
          this.initData(vals[i]);
        }

        /*  if(!this.dictNames) {
            this.dictNames = [val]
          }*/
      } else {
        this.dictNames = [];
      }
    },
    initData(val) {
      this.name = getDictName(this.type, val);
      // console.log('altDict name' , this.dictName , val  , this.type)
      //还是空的话 ajax
      if (
        (this.name == null || this.name == "") &&
        val != null &&
        val != "" &&
        val != undefined &&
        val != "undefined"
      ) { 
        getByTypeValue(this.type , val).then(({ data }) => {
          let hs = false;
          if (data.code === 0) {
            const dict = data.data;
            if (dict != null) {
              this.name = dict.name;
              this.dictNames.push(dict.name);
              // 回填此条数据
              putDict(this.type, dict.name, this.value);
              hs = true;
            }
          }
          if (!hs) {
            this.dictNames.push(val);
          }
        });
      } else {
        this.dictNames.push(this.name);
      }
    }
  }
};
</script>
